------------------------------------------------
---1.从违章队列wzlist取id。 list.pop("r",wzlist)
---2.通过得到的db_data1.id 取redis中的value
---3.将value转化为table,取到gfile1。
---4.将gfile1下载到本地   local str_res = down_storage()
---5.判断车牌是否在红名单中（通过mysql查找）
------5.1 在红名单中就不推送，直接插入del_list
------5.2 不在红名单中
---------将违章车辆的sbbh倒数第5位2改为3
---6.将str_res 通过ftpclient主键上传至ftp服务器
------6.1 ftp 推送失败
---------（重新插入队列等待）：db_data1.id重新插入wzlist  list.push("l",wzlist,db_data1.id)
---------6.2 ftp 推送成功
---7.成功一次将db_data1.id 插入del_list      list.push("l",del_wzlist,db_data1.id)
---8.在ftp服务器端的指定路径(/路口名称-行驶方向/违法图片/yyyyMMdd/图片名称)
-----（没有路径则新建该路径）存入图片



-------1定义公共组件(开始)---------------

local cjson               = require "cjson"
local red_method            = require "gcs.list.method"
local ftpclient             =  require "resty.ftpclient"
local mql_method            = require "gcs.db.method"
local utils                  = require "gcs.utils"
local send_utils               = require "gcs.upload.send_utils"
local storage    = require "resty.gcsdfs.storage"
local config_table            = ngx.shared.gcs_config   --声明ngx.shared.gcs_config
local ipshine_table = ngx.shared.gcs_ipshine
local store_connect_timeout = config_table:get("p_store_connect_timeout")
local store_keep_timeout = config_table:get("p_store_keep_timeout")
local store_keep_count = config_table:get("p_store_keep_count")
local ftp_user = config_table:get("p_ftp_user")
local ftp_pass = config_table:get("p_ftp_pass")
local ftp_host = config_table:get("p_ftp_host")
local ftp_port = config_table:get("p_ftp_port")
local iconv = require("iconv")


-------1定义公共组件（结束）----------------

-------1定义公共组件(结束)---------------


local ftp = ftpclient:new()


local mon = os.date("%Y-%m",ngx.time()) 


local function down_storage(storage_res,tb_value,gfile)
  local str_gfile
  local arg = tb_value
  local st = storage:new()
  st:set_timeout(arg.timeout)
  local ok, err = st:connect(storage_res)
  if not ok then
    return nil,err,1100                             --错误码待定义
  end
  str_gfile,err = st:download_file_to_buff1(gfile)
  if not str_gfile then
    return nil,err,1008
  end

  --关闭storage
  local ok, err = st:set_keepalive(arg.keep_timeout,arg.keep_count)
  return str_gfile
end


function createIconv(from,to,text)        ---编码转换

  local cd = iconv.new(to .. "//TRANSLIT", from)

  local ostr, err = cd:iconv(text)

  if err == iconv.ERROR_INCOMPLETE then
    return nil,"ERROR: Incomplete input."
  elseif err == iconv.ERROR_INVALID then
    return nil,"ERROR: Invalid input."
  elseif err == iconv.ERROR_NO_MEMORY then
    return nil,"ERROR: Failed to allocate memory."
  elseif err == iconv.ERROR_UNKNOWN then
    return nil,"ERROR: There was an unknown error."
  end
  return ostr
end

---------从违章队列wzlist取id--------
local id,err = red_method.pop("r","wzlist")
if tonumber(id) == 0 then
    ngx.exit(200)
end
utils.gcs_log("debug","id已取得"..id)

----------通过得到的id 取redis中的value---
local key = {id}
local res,err = red_method.get_data(key)
if not res then
    utils.gcs_log("error","red_method is fail")
    ngx.exit(200)
end
utils.gcs_log("debug","id对应json已取得")

local function StringSplit(string,split)
  local list = {}
  local pos = 1
  if string.find("", split, 1) then -- this would result in endless loops
    return nil,"split matches empty string!"
  end
  while 1 do
    local first, last = string.find(string, split, pos)
    if first then -- found?
      table.insert(list, string.sub(string, pos, first-1))
      pos = last+1
    else
      table.insert(list, string.sub(string, pos))
      break
    end
  end
  return list
end






local function check_tpmc(tpmc)
   local rt = StringSplit(tpmc,"-")
   
   local tb_sbbh={}
    tb_sbbh[1]=string.sub(rt[15],1,-6)
    tb_sbbh[2]="1"
    tb_sbbh[3]=string.sub(rt[15],-4,-1)
   local sbbh=table.concat(tb_sbbh)
   rt[15]=sbbh
   return table.concat(rt,"-")
end




----------将value转化为table,取到gfile1----

local tb_res = cjson.decode(res[id])
local st_res=cjson.decode(tb_res.str_res1)
local gfile = tb_res.gfile1 
local filename=tb_res.filename1

utils.gcs_log("debug","得到gfile"..gfile)
local fname = tb_res.tpmc1   ------图片名称
local hphm = tb_res.hphm
local date=string.sub(tb_res.time1,1,8)
local date1=string.sub(tb_res.time1,1,6)
utils.gcs_log("debug","hphm"..hphm)
local i,j=string.find(filename,"Plate")
if i then
	 red_method.push("l",date1 .."-wzdellist",id)
	 ngx.exit(200)
end
         
local tb_value={
  timeout = store_connect_timeout,
  keep_timeout = store_keep_timeout,
  keep_count = store_keep_count
}                 

local str_res,err,err_no = down_storage(st_res,tb_value,gfile) 

local fname1=""
local query="select * from base_whitelist where cphm = " ..ngx.quote_sql_str(ngx.md5(hphm))
local res,err=mql_method.query(query)

if not res then
    utils.gcs_log("error","wz_send:mysql" ..err)
    red_method.push("l","wzlist",id)
    ngx.exit(200)
end
if  not next(res)  then --不在白名单中
  local tpmc=check_tpmc(fname)
  fname1=tpmc
else
  local res,err=red_method.push("l",date1 .."-wzdellist",id)
  ngx.exit(200)
end

-----------将str_res 通过ftpclient主键上传至ftp服务器
ftp:set_timeout(10000)
-------封装成函数    连接ftp 若失败重插队列“wzlist”
local res,err = ftp:connect({
                  host = ftp_host,
                  port = ftp_port,
                  user = ftp_user,
                  password = ftp_pass
              })  
                               
if not res then  
utils.gcs_log("error","登陆" ..err)                                   -----------    ftp 推送失败                                               
    local res,err = red_method.push("l","wzlist",id)    ---------重新插入wzlist 
    return
    
end
----------------- ftp 推送成功
-----------新建文件夹
local fx = ""
if tb_res.xsfx == "E" then
    fx = "东"
elseif tb_res.xsfx =="W" then
    fx = "西"
elseif tb_res.xsfx =="N" then
    fx = "北"
else
    fx = "南"
end
local kkmc = ipshine_table:get("kkmc_" .. tb_res.ip)
local dir1 = kkmc.."-" .. fx
local dir1_gbk = createIconv("utf-8","gbk",dir1)
local res,err = ftp:mkd("/" ..dir1_gbk)
local dir2 = dir1.."/违法图片"
local dir2_gbk = createIconv("utf-8","gbk",dir2)
local res,err = ftp:mkd("/" ..dir2_gbk)
local dir3 = dir2 .."/" ..date
local  dir3_gbk = createIconv("utf-8","gbk",dir3)
local res,err = ftp:mkd("/" ..dir3_gbk)  
   
--文件存储 -----------/路口名称-行驶方向/违法图片/yyyyMMdd/图片名称(tpmc)
local res,err=ftp:cwd("/" ..dir3_gbk)
if not res then
    utils.gcs_log("error","cwd err:" ..err)
    red_method.push("l","wzlist",id)
    ngx.exit(200)
end
fname1=fname1 ..".jpg"
local fname1_gbk=createIconv("utf-8","gbk",fname1)
local res,err = ftp:put(fname1_gbk,str_res)
if not res then 
    utils.gcs_log("error","wz_send:ftp" ..err)
    red_method.push("l","wzlist",id)
    ngx.exit(200)
end 
 
ftp:set_keepalive(100,300)        
-------------插入del_list
local res,err = red_method.push("l",date1 .."-wzdellist",id)
utils.gcs_log("info","上传成功")  







